home *** CD-ROM | disk | FTP | other *** search
/ MacTech 1 to 12 / MacTech-vol-1-12.toast / Source / MacTech® Magazine / Volume 11 - 1995 / 11.08 Aug 95 / Dylan Intro Text < prev   
Encoding:
Text File  |  1995-07-14  |  21.5 KB  |  352 lines  |  [TEXT/ttxt]

  1. Namespaces
  2. As you’ve seen, it’s easy to “read” Dylan.  Its syntax is really not that different from C++ or Object Pascal.  One characteristic it does differ in is how namespaces are established and controlled.
  3. In C++, a class definition establishes a namespace encompassing both data members and methods.  Access to class data and functions depends on their public, private and protected nature as established by the class designer.
  4. In Dylan,  a module acts as a namespace.  A module “holds” class and method definitions you choose to group together.  Since Dylan is completely object-oriented, classes, methods, and data are all stored in variables.  You control access to a module variable by choosing whether to “export” it.  Only variables you specifically export are visible outside of that module.  If you don’t export a variable, it is visible only within that module.  This is analogous to C++’s public and private access control mechanisms.
  5. Class Definition
  6. Another difference between Dylan and C++ is in the role classes play.  A C++ class defines member functions which give the class its behavior, and data members which provides context.  In a Dylan class only data is defined.
  7.  
  8. C++ Class Definition
  9. class CEvent : public CObject
  10. {
  11. private:
  12.     short        eventType;
  13.     short        eventPriority;
  14. public:
  15.     CEvent(short type, short priority = kEventPriorityNormal) 
  16.         : eventType(type), eventPriority(priority) {};
  17.     OSErr DoEvent();
  18. };
  19.  
  20. This mythical CEvent class defines two data members: eventType, whose value is the type of event, and eventPriority, which indicates the priority of the event. Its constructor requires two arguments with which it initializes the two data members.  The eventPriority argument is optional, defaulting to a “normal” priority value.  CEvent also defines a DoEvent() method that processes the event.
  21.  
  22. Dylan Class Definition
  23. define class <event> (<object>)
  24.     slot event-type :: <integer>, 
  25.         required-init-keyword: event-type:;
  26.  
  27.     slot event-priority,
  28.         init-keyword: event-priority:, 
  29.         init-value: $event-priority-normal;
  30. end class;
  31.  
  32. Here’s a line-by-line breakdown of the Dylan class definition:
  33.  
  34. define class <event> (<object>) 
  35.  
  36. defines a variable named <event> for the class whose parent class is <object>, the common ancestor of all Dylan classes.  (As you would expect, Dylan supports multiple inheritance.  Additional superclasses would be included, comma-separated, inside the parenthesis.)
  37.  
  38.     slot event-type :: <integer>, 
  39.         required-init-keyword: event-type:;
  40.  
  41. defines a slot (akin to a C++ class data member) named event-type whose data type is limited to integer values.  When an <event> object is instantiated, you are required to supply an initial value for this slot using the event-type: keyword.
  42.  
  43.     slot event-priority, 
  44.         init-keyword: event-priority:, 
  45.         init-value: $event-priority-normal;
  46. defines a untyped slot named event-priority whose keyword initializer is optional.  If you don’t provide it, the slot will default to the value of the $event-priority-normal constant.
  47. As is typical of Dylan block end statements, end class; could have been written just end;, or end class <event>;.
  48. Note that some of the idioms  so often implemented for a C++ class – a constructor to initialize the object’s state, a copy constructor to properly clone the object, and an operator= overload to handle a new value assignment – are not needed.  As shown above, keywords define the slot initialization that takes place when the object is instantiated.  Dylan has built-in functions for copying and assigning objects.  Destructors aren’t required either as automatic memory collection deletes objects that are no longer being referenced.
  49. Data Type Declaration
  50. But what’s with this unspecified data type for the event-priority slot?  In Dylan, type declarations are optional.  From a C++ perspective this lackadaisical approach to data typing seems fraught with peril.  After all, isn’t the strict typing requirements of C++ one of its strengths?
  51. If you write let a-number = 1; (let simply creates a local variable, see Creating and Initializing Variables below) you can trust the compiler to do the right thing.  However there’s nothing preventing you from later setting a-number to a non-integer value, whether you mean to or not.  Dylan allows you to provide data type information when type safety is truly important.  In the example above, all it takes to specifically type a-number as referencing only integer values is to write the statement as  let a-number :: <integer> = 1;
  52. Dylan-ites cite this characteristic of the language as an aid in rapid prototyping.  This reduction in the cognitive load, however slight, has other virtues.  It is pleasant to not have worry about whether a loop counter variable should be a long or a short – what does it matter?  If you leave a-number untyped, the compiler will take care of promoting it to a larger data type should you ever exceed its capacity.   And as illustrated, providing the information necessary to strictly type a variable is easily done.  However, be careful that this new found freedom doesn’t go to your head.  Here’s an example:
  53.  
  54. define variable any-thing = 1;
  55.       // any-thing is untyped, initially references an integer value
  56.  
  57. define variable a-number :: <integer> = 1;
  58.       // a-number is restricted to integer values
  59. /*
  60. note: define variable… creates a module variable which is globally visible within the module. See Creating and Initializing Variables below.
  61. */
  62.  
  63. define method foo ()
  64. /*
  65. note: define method foo() defines a function named foo which takes no arguments. See Generic Functions and Specialized Methods below.
  66. */
  67.  
  68.     any-thing := "a string";
  69.         // OK, any-thing used to reference an integer, now it  references a string
  70.  
  71.     a-number := -1000;
  72.         // OK, still references an integer value
  73.  
  74.     a-number := ‘n’;
  75.         // compiler will complain about type violation since ‘n’ is a character constant,             // not an  integer
  76. end method foo;
  77.  
  78. define method bar()
  79.     a-number := any-thing;
  80.         // compiler will let this pass
  81. end method bar;
  82.  
  83. Since any-thing is untyped, it can contain… well anything.  By the time you call the bar() method, any-thing may have been altered to reference an integer value, so the compiler dares not complain.  Note that the error in the example above is not ignored, it will be caught at run-time.  Fortunately, Dylan’s exception handling capabilities enable you to gracefully recover from such an error.
  84. Instantiating an Object
  85. As mentioned above, Dylan doesn’t expect you to provide an explicit constructor method to initialize an object.  You create an object instance via the make method.
  86.  
  87. let the-event :: <event> = make (<event>, event-type: $some-event);
  88. defines a local variable named the-event of type <event>, and creates an instance of the <event> class, initializing its event-type slot with the value of the $some-event constant.  Since we didn’t provide the event-priority keyword, the event-priority slot is initialized to its defined default value.  The reference to the created instance is assigned to the the-event variable.
  89. There are a number of other slot options you can utilize in your class definitions.  For instance, instead of an explicit default value, you could instead specify an init-function: that is called during object creation to supply the initial value for the slot.
  90. You can also specify how storage for a slot is allocated.  By default, each object instance gets it own storage for a slot.  You can define that a single storage location be used for a slot by a class instance and all its descendants (analogous to a C++ static data member).  Dylan also supports the notion of virtual allocation for a slot.  Storage is not automatically allocated for virtual slots, it is up to you to provide getter and setter methods that retrieve and store the value of the slot.
  91. Slot Accessors
  92. Programmatically, you always access a slot’s value via a function call.  By default, the getter function name is the same as the slot’s name,  and the setter function is the getter’s name appended with “-setter”.  Continuing with our <event> class example above,  to retrieve the slot’s value you would call: 
  93.  
  94.     event-type(the-event);
  95.  
  96. and to set the event type you would call:
  97.  
  98.     event-type-setter($some-event, the-event);
  99.  
  100. Dylan kindly provides some syntactic sugar in this regard.  It also allows the more conventional ‘object.slot’ syntax.  The following forms are equivalent:
  101.  
  102. Getters
  103.                 event-type(the-event)
  104.                 the-event.event-type
  105. Setters
  106.                 event-type-setter($some-event, the-event);
  107.                 the-event.event-type := $some-event;
  108.                 event-type(the-event) := $some-event;
  109.  
  110. The use of the assignment operator := in the alternate setter is discussed in Creating and Initializing Variables below.
  111. In addition to the slot options mentioned in the discussion above on class declarations, you can also specify the names for the slot’s getter and setter accessor functions.  You may also protect a slot’s value from modification (i.e. make it read-only.)
  112. Generic Functions and Specialized Methods
  113. OK – we’ve defined an <event> class, we know how to instantiate one, and by default Dylan provided getter and setter functions for its slots.  Big deal! – we didn’t define any class member functions.  So how in the world do we use the bloody thing?
  114. In Dylan, the term generic function refers a family of methods that share the same name and basic arguments.  A specialized method  is a member of a generic function family whose arguments are specialized to act upon a particular object or object type.  When you call a generic function, Dylan looks at all the arguments you provide to determine the most specific method to call.
  115. To explore how this form of polymorphic method dispatch works, we need to first refine our design. Let’s add a subclass of <event> specifically for window events, and another for mouse events.
  116.  
  117. define class <window-event> (<event>)
  118.     slot window :: <window>, 
  119.         init-value: $nil-window, 
  120.         init-keyword: window:;
  121. end class;
  122.  
  123. define class <mouse-event> (<event>)
  124.     slot local-coordinates, init-value: #f;
  125. end class;
  126.  
  127. (Note that the <window> class is for illustrative purposes only, it is obviously not intrinsic to the language.  However, the Apple Dylan application framework does contain a window class and many other Macintosh-related classes.)
  128.  
  129. Now let’s provide specialized methods to handle these events:
  130.  
  131. define method do-event (event :: <event>)
  132.     // basic event handling
  133. end method;
  134.  
  135. define method do-event(event :: <window-event>)
  136.     // window-specific event handling
  137. end method;
  138.  
  139. define method do-event(event :: <mouse-event>)
  140.     // mouse-specific event handling
  141. end method;
  142.  
  143. When your event detection code calls the do-event generic function, the specific method that gets run depends on the event subclass of the object passed as the parameter.  For instance, in response to a mouse event, you would instantiate a <mouse-event> object  and pass it as the argument to do-event.  All members of the do-event family are examined to see which method most closely resembles the objects passed as arguments.  In this example the do-event(event :: <mouse-event>) specialized method is invoked.  In many cases the compiler will be able to make this analysis and generate code that directly calls the most specific method thus incurring no runtime penalty.
  144. Methods pass control to the next most specialized method by calling next-method(), which is similar to calling Inherited in Object Pascal, or invoking the direct superclass method via CSuperclass:Method() in C++.  For example, the do-event(event :: <mouse-event>) specialized method may need to run the event handling code contained in the base do-event (event :: <event>) method before its code is run.
  145. In contrast, C++’s polymorphic method dispatch depends on common ancestry.  Every class that needs to handle an event must (in our example) descend from CEvent, and with each new event that is added, the class hierarchy must be altered.  In Dylan, you just define the new class and add a method specialized on the new event type.  Dylan’s approach reduces class coupling and minimizes the impact on existing code when new functionality is introduced.  If nothing else, it “feels” more natural.  Instead of thinking “event-class, handle the mouse event”, it’s just, “handle the mouse event.”  I know this difference seems trivial, but to me it is the critical difference between C++ and Dylan.
  146. Finally, note that methods, like classes, are first-class objects.  That means they can be assigned to a variable and passed around like any other variable.  Yah, weird… Local Methods below gives an example of how powerfully weird this feature can be.
  147. Method Parameter Lists
  148. In addition to required parameters, a method’s parameter list can be defined to accept an unlimited number of arguments.
  149.  
  150. define method plot-points(#rest points-to-plot); 
  151.  
  152. defines a method named plot-points that accepts a variable number of arguments.  Parsing the point arguments inside the method is easily done via:
  153.  
  154.     for (a-point in points-to-plot) // plot each point provided
  155.       draw-point(a-point);
  156.   end for;
  157. end method plot-points;
  158.  
  159. To call this method, you merely pass all the points you want:
  160.  
  161. plot-points(point-a, point-b, point-c);
  162.  
  163. Method parameter lists can also define optional keyworded parameters. For instance,
  164.  
  165. define method make-window (dimensions, #key title = "Untitled", 
  166.                                                                                     has-zoom-box?)
  167.  
  168. defines a method that has one required argument, dimensions, and two optional keyword arguments.  If the title keyword is not specified, its value is “Untitled”.  If has-zoom-box? is not specified its value is false (#f).  You can specify keywords in any order, as shown below:
  169.  
  170. make-window(window-size, has-zoom-box?: #t, title: "New Window");
  171. Return Values
  172. OK, here’s a quiz.  What does this method return?
  173.  
  174.  
  175. define method square-of(x :: <integer>)
  176.   x * x;
  177. end method;
  178.  
  179. Not real obvious, is it?  In Dylan there is no explicit return statement – the result of a function is whatever value is generated by the last expression in the method, in this case x * x.  If you were just browsing through the method definitions in a module, it wouldn’t be immediately apparent that this method returned anything at all.  Luckily, Dylan allows you the option of declaring the result type of a method :
  180.  
  181. define method square-of (x :: <integer>) 
  182.                                         => x-squared :: <integer>; // => result value
  183.   x * x;
  184. end method;
  185.  
  186. The inclusion of => x-squared :: <integer>; reveals that the method returns an integer value.  Note that just => x-squared; is legal as well. Unfortunately this is pretty much useless, other than as an indication that the method returns a result of some undetermined data type.  Note as well that the name of the result value, x-squared in this example, never comes into scope.  So it can be any valid identifier: the-result, x*x, square-of, <integer>, or omitted altogether.  I’ve made a habit of always explicitly defining a method’s result values, and giving them meaningful names.  Just because Dylan will let us be lazy is no reason to do so.
  187. One feature of Dylan I have grown fond of is the ability of an expression to return multiple values using the values function.   For example, let’s pretend we have a C++ method that accepts a Rect, and returns its height and width.  In C++ you would declare:
  188.  
  189. void RectSize(Rect& rect, short& height, short& width)
  190. {
  191.     height = a-rect.bottom - a-rect.top;
  192.     width = a-rect.right - a-rect.left;
  193. }
  194.  
  195. and call it by:
  196.  
  197. RectSize(rect, h, w);
  198.  
  199. In Dylan you could instead:
  200.  
  201. define method rect-size(a-rect) 
  202.                             => (height :: <integer>, width :: <integer>);
  203.   values(a-rect.bottom - a-rect.top, 
  204.                     a-rect.right - a-rect.left);
  205. end method;
  206.  
  207. let (h, w) = rect-size(a-rect);
  208.  
  209. Note that like the <point> class shown above, <rect> is not an intrinsic Dylan class, but it is a part of the Apple Dylan application framework.
  210. Local Methods
  211. Quite frankly, there’s very little I miss about my Object Pascal programming days, except local procedures and the availability of class meta-data.  For those of you untainted by Pascal, local procedures are small, special purpose procedures that can be embeded inside another procedure.  They’re neat, clean and don’t clutter up your interface.  Dylan’s got ‘em too.  The special form local is used to bind a variable (and hence methods) within the current scope.  Here’s an example:
  212.  
  213. define method plot-random-point() => ()  // returns nothing
  214.     local
  215.         method compute-random(max-value)
  216.                                                         => random-value :: <integer>;
  217.             let r = remainder(Random(), max-value);
  218.                 // remainder is a built-in Dylan function
  219.                 // Random() is the Mac Toolbox trap
  220.             if (r < 0) 
  221.                 - r        // => compute-random returns (- r)
  222.             else 
  223.                 r            // => compute-random returns r
  224.             end if;
  225.         end method compute-random;
  226.  
  227.     let (h, w) = screen-dimensions();  
  228.         // screen-dimensions returns screen height and width
  229.  
  230.     draw-point(make(<point>, 
  231.                                                 h: compute-random(h),
  232.                                                 v: compute-random(w) ));
  233.  
  234. end method plot-random-point;
  235.  
  236. A local method’s scope is that of its enclosing method, it has access to the parameter list, and any other methods created within the local block.  However, you can use a local method outside of this scope.  For instance, if you were doing some sort of analysis where the function to be performed depends entirely on the object under scrutiny, you could define a method that looks at the object and returns the proper function:
  237.  
  238. define method analyze-me(patient) => analyst :: <method>;  
  239.                                                                         // <method> is a built-in class
  240.  
  241.     local method freudian () ... end;
  242.     local method jungian () ... end;
  243.  
  244.     if (blames-mother(patient))
  245.         freudian // returns the freudian method, does not execute it
  246.     else
  247.          jungian // returns the jungian method, does not execute it
  248.     end if;
  249. end analyze-me;
  250.  
  251. let axe-dude = analyze-me(alan-bates);
  252.     // this creates and returns a function
  253.  
  254. axe-dude();  
  255.     // this invokes the local method in its original scope (patient = alan-bates)
  256. Creating and Initializing Variables
  257. Like Bob’s Country Bunker where they have two kinds of music: country AND western, Dylan supports two kinds of variables: module and lexical.
  258. Module variables can be referenced from anywhere inside the module, i.e. they are “global.”  A module variable is created using:
  259.  
  260. define variable *current-temperature* = 55;  
  261.                                                                         // the high today in Seattle…
  262.  
  263. You can, as noted above, associated a data type with the variable name, and by convention, variables whose value will change begin and end with asterisks.
  264. Module constants (read-only variables) are defined in similar style:
  265.  
  266. define constant $the-meaning-of-Life = 42;
  267. Variable names for constants, by convention, begin with a $ character.
  268.  
  269. A lexical, or local, variable is created using: 
  270.  
  271. let counter = 0;
  272. let binds a new name to an existing object.  This is unlike assignment, which alters the contents of an existing storage location.  
  273. Like C, a local variable’s scope is limited to the smallest enclosing block in which it occurs.  For instance, outside of this  if block:
  274.  
  275. define method how-loud?(album) => level :: <integer>;  
  276.     if (album = "Smell the Glove")
  277.         let volume = 11
  278.     else
  279.         let volume = 10
  280.     end if;
  281.     volume;  // => how-loud? result
  282. end method;
  283.  
  284. volume doesn’t exist and so the compiler won’t be able to make sense of the last line.  volume was created by a let statement inside the if block, and fell out of scope when it was exited.  What you want to do is:
  285.  
  286. define method how-loud?(album) => level :: <integer>;  
  287.     let volume =
  288.         if (album = "Smell the Glove")
  289.             11        // => result of 'if' assigned to volume
  290.         else
  291.             10        // => alternate result
  292.         end if;
  293.     volume; // => method result
  294. end method;
  295.  
  296. But a true Dylan-Weenie would drop the references to volume altogether and return the result of the if statement:
  297.  
  298. define method how-loud?(album) => level :: <integer>;  
  299.     if (album = "Smell the Glove")
  300.         11  // => result
  301.     else
  302.         10  // => result
  303.     end if;
  304. end method;
  305. Assigning Values to Variables
  306. I’d like to tidy up a few loose ends regarding assignment and equality which illustrate some important Dylan precepts.  The special form := was introduced earlier.  Unlike C, which uses the = to assign a value, Dylan uses := to assign a different value to an extant variable. 
  307.  
  308. define variable counter = 10;
  309. define variable delta = 20;
  310. counter := counter + delta;  // counter now set to 30
  311.  
  312. := can also be used as an alternate form for setter functions.  Recalling our Slot Accessors discussion above,
  313.  
  314.         event-type-setter($some-event, the-event);
  315. can also be written:
  316.  
  317.         the-event.event-type := $some-event;
  318.  
  319. It’s important to note that assigning the contents of one variable to another does not copy the object being referred to.
  320.  
  321.         let the-joker.enemy = batman;  
  322.         let the-penguin.enemy = the-joker.enemy;
  323.  
  324. the-penguin.enemy slot doesn’t reference a copy of the batman object, it references the very same object as does the-joker.enemy slot.  If you alter batman, mutating it into his alter ego, then both the-joker and the-penguin “see” the change.
  325. Equality Testing
  326. The = function is used as an equivalence test, and == is used to test for uniqueness.  To explore the difference, let me present <vector>, one of Dylan’s many built-in collection classes.  Vectors are simply one-dimensional arrays.
  327.  
  328. let vector-A = vector(1, 2, 3);
  329.         // creates a vector of 3 elements: 1, 2 and 3
  330.  
  331. let vector-B = vector(1, 2, 3);
  332.         // creates another vector which does not share storage with the first
  333.  
  334. (vector-A = vector-B);
  335.         // => true.  the two vectors are equivalent - their contents “appear” the same
  336.  
  337. (vector-A == vector-B);
  338.         // => false!  the two vectors are separate objects, and so are unique
  339.  
  340. let vector-C = vector-A;
  341.         // now the first vector is known by two names:
  342.         //   vector-A and vector-C
  343.  
  344. (vector-A = vector-C);
  345.         // => true.  the two vectors are equivalent
  346.  
  347. (vector-A == vector-C);
  348.         // => true!  vector-A and vector-C reference the same object
  349.         
  350.         
  351.         
  352.